from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.utils import timezone
from django.contrib.auth.hashers import make_password, check_password

# Create your models here. 

# 用户管理器
class UserManager(BaseUserManager):
    def create_user(self, username, password=None, **extra_fields):
        """创建普通用户"""
        if not username:
            raise ValueError('用户名是必填项')
        
        user = self.model(username=username, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user
    
    def create_superuser(self, username, password=None, **extra_fields):
        """创建超级用户"""
        extra_fields.setdefault('is_admin', True)
        
        return self.create_user(username, password, **extra_fields)

# 用户模型
class User(AbstractBaseUser, PermissionsMixin):
    """
    用户模型 (对应数据库tb_user表)
    
    使用Django的ORM但不创建表，而是映射到现有表
    """
    user_id = models.BigAutoField(primary_key=True)
    username = models.CharField(max_length=50, unique=True, verbose_name='用户名')
    password = models.CharField(max_length=255, verbose_name='密码')
    phone = models.CharField(max_length=20, null=True, blank=True, verbose_name='手机号')
    email = models.EmailField(max_length=100, null=True, blank=True, verbose_name='电子邮箱')
    icon = models.CharField(max_length=255, null=True, blank=True, verbose_name='头像URL')
    mq_points = models.IntegerField(default=0, verbose_name='妙趣积分')
    saved_amount = models.DecimalField(max_digits=10, decimal_places=2, default=0.00, verbose_name='累计节省金额')
    reduced_waste = models.DecimalField(max_digits=10, decimal_places=2, default=0.00, verbose_name='减少浪费量')
    badge_count = models.IntegerField(default=0, verbose_name='徽章数量')
    voucher_count = models.IntegerField(default=0, verbose_name='优惠券数量')
    create_time = models.DateTimeField(default=timezone.now, verbose_name='创建时间')
    last_login = models.DateTimeField(null=True, blank=True, verbose_name='最后登录时间')
    is_admin = models.BooleanField(default=False, verbose_name='是否管理员')
    
    objects = UserManager()
    
    USERNAME_FIELD = 'username'
    EMAIL_FIELD = 'email'
    REQUIRED_FIELDS = []
    
    class Meta:
        managed = False
        db_table = 'tb_user'
        app_label = 'accounts'
        verbose_name = '用户'
        verbose_name_plural = '用户'
    
    def __str__(self):
        return self.username
    
    def set_password(self, raw_password):
        """设置密码"""
        self.password = make_password(raw_password)
        self._password = raw_password
    
    def check_password(self, raw_password):
        """验证密码，同时支持明文密码和哈希密码"""
        if raw_password == self.password:  # 兼容旧密码存储方式
            return True
        return check_password(raw_password, self.password)
    
    @property
    def is_staff(self):
        """是否为员工，用于Django admin访问"""
        return self.is_admin
    
    @property
    def is_superuser(self):
        """是否为超级用户"""
        return self.is_admin
    
    @property
    def is_active(self):
        """是否为活跃用户"""
        return True  # 所有用户默认为活跃状态
    
    def get_addresses(self):
        """获取用户地址"""
        return Address.objects.filter(user_id=self.user_id)
    
    def get_point_records(self, limit=10):
        """获取积分记录"""
        return PointRecord.objects.filter(user_id=self.user_id).order_by('-create_time')[:limit]

# 收货地址模型
class Address(models.Model):
    """
    收货地址模型 (对应数据库tb_address表)
    """
    address_id = models.BigAutoField(primary_key=True)
    user_id = models.BigIntegerField(db_index=True)
    receiver = models.CharField(max_length=50)
    phone = models.CharField(max_length=20)
    province = models.CharField(max_length=20, null=True, blank=True)
    city = models.CharField(max_length=20, null=True, blank=True)
    district = models.CharField(max_length=20, null=True, blank=True)
    detail = models.CharField(max_length=255)
    is_default = models.BooleanField(default=False)
    create_time = models.DateTimeField(auto_now_add=True)
    update_time = models.DateTimeField(auto_now=True)
    
    # 关联User模型，使用不同的db_column避免冲突
    user_obj = models.ForeignKey(User, on_delete=models.CASCADE, related_name='addresses', db_column='user_id_fk', to_field='user_id')
    
    class Meta:
        managed = False
        db_table = 'tb_address'
        app_label = 'accounts'
        verbose_name = '收货地址'
        verbose_name_plural = '收货地址'
    
    def __str__(self):
        return f"{self.receiver} - {self.phone} - {self.province}{self.city}{self.district}{self.detail}"

# 积分记录模型
class PointRecord(models.Model):
    """
    积分记录模型 (对应数据库tb_point_record表)
    """
    record_id = models.BigAutoField(primary_key=True)
    user_id = models.BigIntegerField(db_index=True)
    points = models.IntegerField()
    type = models.SmallIntegerField(default=1) 
    description = models.CharField(max_length=255, null=True, blank=True)
    reference_id = models.BigIntegerField(null=True, blank=True)
    create_time = models.DateTimeField(default=timezone.now)
    
    # 关联User模型，使用不同的db_column避免冲突
    user_obj = models.ForeignKey(User, on_delete=models.CASCADE, related_name='point_records', db_column='user_id_fk', to_field='user_id')
    
    class Meta:
        managed = False
        db_table = 'tb_point_record'
        app_label = 'accounts'
        verbose_name = '积分记录'
        verbose_name_plural = '积分记录'
    
    def __str__(self):
        user_name = self.user_obj.username if hasattr(self, 'user_obj') else f"用户{self.user_id}"
        return f"{user_name} - {'+' if self.points > 0 else ''}{self.points}"
    
    @property
    def type_name(self):
        """积分类型名称"""
        type_map = {
            1: '购买盲盒',
            2: '评价',
            3: '签到',
            4: '兑换',
            5: '活动',
        }
        return type_map.get(self.type, '未知') 